import * as fs from 'fs';
import * as path from 'path';
import { BrowserConfig } from './types';
import * as os from 'os';

export function generateUserAgent(): string {
  // 浏览器类型和版本配置
  const browsers = {
    chrome: {
      versions: ['114.0.0.0', '115.0.0.0', '116.0.0.0', '117.0.0.0', '118.0.0.0', '119.0.0.0', '120.0.0.0', '121.0.0.0'],
      webkitVersions: ['537.36', '537.37', '537.38', '537.39', '537.40', '537.41', '537.42', '537.43'],
      generate: (os: string, version: string, webkit: string) => 
        `Mozilla/5.0 (${os}) AppleWebKit/${webkit} (KHTML, like Gecko) Chrome/${version} Safari/${webkit}`
    },
    firefox: {
      versions: ['114.0', '115.0', '116.0', '117.0', '118.0', '119.0', '120.0', '121.0'],
      webkitVersions: [], // Firefox不使用WebKit，但为了类型兼容性添加空数组
      generate: (os: string, version: string, webkit?: string) => 
        `Mozilla/5.0 (${os}; rv:${version}) Gecko/20100101 Firefox/${version}`
    },
    safari: {
      versions: ['16.0', '16.1', '16.2', '16.3', '16.4', '16.5', '16.6', '17.0', '17.1', '17.2'],
      webkitVersions: ['605.1.15', '605.1.16', '605.1.17', '605.1.18', '605.1.19', '605.1.20'],
      generate: (os: string, version: string, webkit: string) => 
        `Mozilla/5.0 (${os}) AppleWebKit/${webkit} (KHTML, like Gecko) Version/${version} Safari/${webkit}`
    },
    edge: {
      versions: ['114.0.1823.0', '115.0.1901.0', '116.0.1938.0', '117.0.2045.0', '118.0.2088.0', '119.0.2151.0', '120.0.2210.0', '121.0.2277.0'],
      webkitVersions: ['537.36', '537.37', '537.38', '537.39', '537.40', '537.41', '537.42', '537.43'],
      generate: (os: string, version: string, webkit: string) => 
        `Mozilla/5.0 (${os}) AppleWebKit/${webkit} (KHTML, like Gecko) Chrome/${version} Safari/${webkit} Edg/${version}`
    },
    opera: {
      versions: ['100.0.4815.0', '101.0.4843.0', '102.0.4880.0', '103.0.4928.0', '104.0.4944.0', '105.0.4970.0'],
      webkitVersions: ['537.36', '537.37', '537.38', '537.39', '537.40', '537.41', '537.42', '537.43'],
      generate: (os: string, version: string, webkit: string) => 
        `Mozilla/5.0 (${os}) AppleWebKit/${webkit} (KHTML, like Gecko) Chrome/${version} Safari/${webkit} OPR/${version}`
    }
  };

  const platforms = {
    win: {
      os: 'Windows NT 10.0; Win64; x64',
      platform: 'Windows'
    },
    mac: {
      os: 'Macintosh; Intel Mac OS X 10_15_7',
      platform: 'macOS'
    },
    linux: {
      os: 'X11; Linux x86_64',
      platform: 'Linux'
    }
  } as const;

  // 随机选择浏览器类型
  const browserTypes = Object.keys(browsers) as (keyof typeof browsers)[];
  const randomBrowserType = browserTypes[Math.floor(Math.random() * browserTypes.length)];
  const browser = browsers[randomBrowserType];

  // 随机选择平台
  const platformKeys = ['win', 'mac', 'linux'] as const;
  const randomPlatform = platforms[platformKeys[Math.floor(Math.random() * platformKeys.length)] as keyof typeof platforms];

  // 随机选择版本
  const randomVersion = browser.versions[Math.floor(Math.random() * browser.versions.length)];

  // 根据浏览器类型生成UA
  if (randomBrowserType === 'firefox') {
    return (browser as any).generate(randomPlatform.os, randomVersion);
  } else {
    // Chrome、Safari、Edge、Opera 都需要 WebKit 版本
    const randomWebKit = (browser as any).webkitVersions[Math.floor(Math.random() * (browser as any).webkitVersions.length)];
    return (browser as any).generate(randomPlatform.os, randomVersion, randomWebKit);
  }
}

export async function withTimeout<T>(promise: Promise<T>, timeoutMs: number = 2000): Promise<T> {
  return Promise.race([
    promise,
    new Promise<T>((_, reject) => setTimeout(() => reject(new Error('timeout')), timeoutMs))
  ]);
}

export function getChromePath(): string {
  // 获取Chrome可执行文件路径
  let appPath: string;
  
  console.log('Current NODE_ENV:', process.env.NODE_ENV);
  console.log('Current __dirname:', __dirname);
  console.log('Current process.resourcesPath:', process.resourcesPath);
  
  if (process.env.NODE_ENV === 'development') {
    // 开发环境：从项目根目录的chromium获取
    appPath = path.join(__dirname, '../../chromium/chrome.exe');
    console.log('Development mode - using path:', appPath);
  } else {
    // 生产环境：从打包后的resources/app.asar.unpacked/chromium获取
    appPath = path.join(process.resourcesPath, 'app.asar.unpacked/chromium/chrome.exe');
    console.log('Production mode - using path:', appPath);
  }
  
  try {
    console.log('Chrome path:', appPath);
    const stats = fs.statSync(appPath);
    if (stats.isFile()) {
      console.debug(`Using bundled Chromium at: ${appPath}`);
      return appPath;
    }
  } catch (error) {
    console.debug(`Bundled Chromium not found at: ${appPath}`);
    console.error('Error details:', error);
  }

  throw new Error('找不到Chrome浏览器，请确保项目根目录下存在chromium/chrome.exe文件');
}

export function cleanUserDataDirectory(userDataDir: string) {
  try {
    const filesToClean = [
      'SingletonLock',
      'SingletonSocket',
      'Singleton'
    ];

    for (const file of filesToClean) {
      const filePath = path.join(userDataDir, file);
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    }
  } catch (error) {
    console.error('Failed to clean user data directory:', error);
  }
}

export function validateBrowserConfig(config: BrowserConfig): boolean {
  if (!config) return false;
  if (typeof config.id !== 'string' || !config.id.trim()) return false;
  if (typeof config.name !== 'string' || !config.name.trim()) return false;
  
  // 检查ID格式
  if (!/^\d+$/.test(config.id)) return false;
  
  // 检查名称长度
  if (config.name.length > 50) return false;
  
  // 验证代理配置
  if (config.proxy) {
    if (typeof config.proxy.enabled !== 'boolean') return false;
    
    if (config.proxy.enabled) {
      // 如果启用代理，必须提供有效的配置
      if (typeof config.proxy.host !== 'string' || !config.proxy.host.trim()) return false;
      if (typeof config.proxy.port !== 'number' || config.proxy.port < 1 || config.proxy.port > 65535) return false;
      if (!['http', 'https', 'socks4', 'socks5'].includes(config.proxy.type)) return false;
      
      // 验证主机地址格式
      const hostRegex = /^[a-zA-Z0-9.-]+$/;
      if (!hostRegex.test(config.proxy.host)) return false;
      
      // 如果提供了用户名，密码也必须提供
      if (config.proxy.username && !config.proxy.password) return false;
      if (config.proxy.password && !config.proxy.username) return false;
      
      // 验证用户名和密码长度
      if (config.proxy.username && (config.proxy.username.length < 1 || config.proxy.username.length > 100)) return false;
      if (config.proxy.password && (config.proxy.password.length < 1 || config.proxy.password.length > 100)) return false;
      
      // 验证用户名和密码字符
      const authRegex = /^[a-zA-Z0-9._-]+$/;
      if (config.proxy.username && !authRegex.test(config.proxy.username)) return false;
      if (config.proxy.password && !authRegex.test(config.proxy.password)) return false;
    }
  }
  
  return true;
}

/**
 * 获取主网卡的MAC地址
 * @returns 返回第一个有效的MAC地址，如果没有找到则返回null
 */
export function getMacAddress(): string | null {
  try {
    const networkInterfaces = os.networkInterfaces();
    
    // 遍历所有网络接口
    for (const interfaceName in networkInterfaces) {
      const interfaces = networkInterfaces[interfaceName];
      if (interfaces) {
        for (const iface of interfaces) {
          // 跳过内部接口和IPv6地址
          if (!iface.internal && iface.family === 'IPv4' && iface.mac) {
            // 过滤掉无效的MAC地址（全0或特殊地址）
            if (iface.mac !== '00:00:00:00:00:00' && 
                iface.mac !== 'ff:ff:ff:ff:ff:ff' &&
                iface.mac.length === 17) {
              return iface.mac;
            }
          }
        }
      }
    }
    
    // 如果没有找到有效的MAC地址，返回null
    return null;
  } catch (error) {
    console.error('获取MAC地址失败:', error);
    return null;
  }
}

/**
 * 获取所有网络接口的MAC地址
 * @returns 返回所有网络接口的MAC地址数组
 */
export function getAllMacAddresses(): string[] {
  try {
    const networkInterfaces = os.networkInterfaces();
    const macAddresses: string[] = [];
    
    for (const interfaceName in networkInterfaces) {
      const interfaces = networkInterfaces[interfaceName];
      if (interfaces) {
        for (const iface of interfaces) {
          if (!iface.internal && iface.family === 'IPv4' && iface.mac) {
            if (iface.mac !== '00:00:00:00:00:00' && 
                iface.mac !== 'ff:ff:ff:ff:ff:ff' &&
                iface.mac.length === 17) {
              macAddresses.push(iface.mac);
            }
          }
        }
      }
    }
    
    return macAddresses;
  } catch (error) {
    console.error('获取所有MAC地址失败:', error);
    return [];
  }
} 